package com.xu.cloud.common.api;

import com.xu.cloud.common.pojo.http.req.BaseRequest;
import com.xu.cloud.common.pojo.http.resp.BaseResponse;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * api请求参数
 *
 * @author xuguan
 * @since 2024/1/9
 */
@Data
public class ApiContext {
    /**
     * 全局traceId
     */
    private String traceId;
    /**
     * 请求流水号
     */
    private String reqJournalNo;
    /**
     * api code
     */
    private String apiCode;
    /**
     * 请求路径
     */
    private String apiPath;
    /**
     * 客户端IP
     */
    private String clientIp;
    /**
     * 请求时间
     */
    private LocalDateTime reqTime;
    /**
     * 响应时间
     */
    private LocalDateTime respTime;
    /**
     * 请求参数实体类
     */
    private BaseRequest baseRequest;
    /**
     * 请求参数实体类
     */
    private BaseResponse baseResponse;
    /**
     * HttpServletRequest请求参数实体类
     */
    private HttpServletRequest httpServletRequest;
    /**
     * HttpServletResponse响应参数实体类
     */
    private HttpServletResponse httpServletResponse;
    /**
     * 响应码
     */
    private String code;
    /**
     * 响应信息
     */
    private String msg;
    /**
     * 具体的异常类
     */
    private Throwable throwable;
    /**
     * 交易执行时间（毫秒）
     */
    private long transCostMillis;
    /**
     * 额外参数
     */
    private final Map<String, Object> properties = new ConcurrentHashMap<>();

    public Object getProperty(String key) {
        return properties.get(key);
    }

    public <T> T getProperty(String key, Class<T> cls) {
        return cls.cast(properties.get(key));
    }

    public void setProperty(String key, Object value) {
        properties.put(key, value);
    }

    public static ApiContext current() {
        return ApiContextHolder.getOrSetTransContext();
    }
}
